package top.syfy.xml;

import org.jdom2.Attribute;
import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.JDOMException;
import org.jdom2.input.SAXBuilder;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;

/**
 *
 * JDOM方式解析XML文件
 */
public class ParseByJdom {

    public static void main( String[] args ) throws IOException, JDOMException {
        // 创建SAXBuilder对象
        SAXBuilder builder = new SAXBuilder();
        // 创建输入流
        InputStream in = new FileInputStream(new File("example.xml"));
        // 将输入流加载到SAXBuilder中
        Document document = builder.build(in);
        // 获取根节点
        Element rootElement = document.getRootElement();
        // 获取子节点student
        List<Element> studentElementList = rootElement.getChildren();
        for (Element stuEle:studentElementList) {
            // 遍历student节点的属性
            List<Attribute> attributeList = stuEle.getAttributes();
            for (Attribute attribute:attributeList) {
                System.out.println("属性: " + attribute.getName() + "=" + attribute.getValue());
            }
            // 遍历student节点的子节点
            List<Element> studentSubElementList = stuEle.getChildren();
            for (Element sub:studentSubElementList) {
                System.out.println("节点: " + sub.getName() + "=" + sub.getValue());
            }
            System.out.println("=========================");
        }
    }
}
